package com.cwd.arm.domain.repository.impl;

import com.cwd.arm.domain.entity.TaxEntity;
import com.cwd.arm.domain.repository.ProjectRepository;
import com.cwd.arm.domain.repository.TaxRepository;
import com.cwd.arm.infrastructure.dao.ReceiveRecordDao;
import com.cwd.arm.infrastructure.po.ReceiveRecordPo;
import com.cwd.arm.domain.entity.ReceiveRecordEntity;
import com.cwd.arm.domain.repository.ReceiveRecordRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
* Description:收款记录
* Created on 2021年11月16日
* @author  yan
*/
@Repository
public class ReceiveRecordRepositoryImpl implements ReceiveRecordRepository{

    @Autowired
    private ReceiveRecordDao dao;

    @Autowired
    private TaxRepository taxRepository;

    @Autowired
    private ProjectRepository projectRepository;

    @Override
    public void save(ReceiveRecordEntity receiveRecordEntity) {
        TaxEntity taxEntity = taxRepository.buildTaxEntity(receiveRecordEntity.getTaxId());
        dao.save(convertToReceiveRecordPo(receiveRecordEntity,taxEntity));
        taxRepository.addRecord(taxEntity,receiveRecordEntity);
        projectRepository.updateReceiveCycle(taxEntity.getProjectId());
    }

    @Override
    public void update(ReceiveRecordEntity receiveRecordEntity) {
        ReceiveRecordEntity oldReceiveRecordEntity = buildReceiveRecordEntity(receiveRecordEntity.getId());
        TaxEntity taxEntity = taxRepository.buildTaxEntity(oldReceiveRecordEntity.getTaxId());
        dao.updateById(convertToReceiveRecordPo(receiveRecordEntity,taxEntity));
        taxRepository.updateRecord(taxEntity,oldReceiveRecordEntity,receiveRecordEntity);
        projectRepository.updateReceiveCycle(taxEntity.getProjectId());
    }

    @Override
    public void del(Long id) {
        ReceiveRecordEntity receiveRecordEntity = buildReceiveRecordEntity(id);
        TaxEntity taxEntity = taxRepository.buildTaxEntity(receiveRecordEntity.getTaxId());
        dao.removeById(id);
        taxRepository.delRecord(taxEntity,receiveRecordEntity);
    }

    private ReceiveRecordPo convertToReceiveRecordPo(ReceiveRecordEntity entity,TaxEntity taxEntity){
        ReceiveRecordPo receiveRecordPo = new ReceiveRecordPo();
        BeanUtils.copyProperties(entity,receiveRecordPo);
        receiveRecordPo.setProjectId(taxEntity.getProjectId());
        receiveRecordPo.setReceiveNodeId(taxEntity.getReceiveNodeId());
        return receiveRecordPo;
    }

    private ReceiveRecordEntity buildReceiveRecordEntity(Long id){
        ReceiveRecordEntity receiveRecordEntity = new ReceiveRecordEntity();
        ReceiveRecordPo po = dao.getById(id);
        BeanUtils.copyProperties(po,receiveRecordEntity);
        return receiveRecordEntity;
    }

}
